#!/usr/bin/python
# -*- coding: utf-8 -*-

#Author: Yuanhao Li <jay_21cn@hotmail.com>
#File: ingcthreads.py
#Usage: Client of ING from project Babel
#Copyright (C) 2007 Yuanhao Li<jay_21cn@hotmail.com>

#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software Foundation,
#Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#本程序是遵从 GPL 2.0 许可发布的. 你可以自由修改和再发布本程序, 
#但请遵守 GPL 2.0 条款, 尊重知识产权.

import urllib, sys, os

from PyQt4 import QtCore
from PyQt4.QtCore import QThread, QObject, QRegExp, QString

cwd = os.path.split(sys.argv[0])[0]
if not cwd:
	cwd = os.getcwd()

class ThreadLogin(QThread):
	def __init__(self, babel):
		QThread.__init__(self)
		self.babel = babel
		self.stop = True

	def run(self):
		self.stop = False
		self.babel.login()
		self.emit(QtCore.SIGNAL("doLogin"))
		self.stop = True

class ThreadGetNewItems(QThread):
	def __init__(self, rss):
		QThread.__init__(self)
		self.rss = rss
		self.running = True
		self.sleeptime = 30
		self.stop = True

	def setSleepTime(self, time):
		self.sleeptime = time

	def run(self):
		self.stop = False
		while self.running:
			if self.rss.parseNewItems():
				self.emit(QtCore.SIGNAL("hasNewItems"), self)
			self.emit(QtCore.SIGNAL("requestedOnce"))
			QThread.sleep(self.sleeptime)
		self.stop = True

	def setRunning(self, running):
		self.running = running

class ThreadRequestHotTopics(QThread):
	def __init__(self, babel):
		QThread.__init__(self)
		self.babel = babel
		self.stop = True

	def run(self):
		# here is not good for encapsulate.the function body should in class Babel... 
		self.stop = False
		url = self.babel.getUrl() + '/sidebar.html'
		data = ''
		try:
			if self.babel.getProxy() == '':
				data = urllib.urlopen(url).read().decode('utf-8', 'replace')
			else:
				proxies = {'http':self.babel.getProxy()}
				opener = urllib.FancyURLopener(proxies)
				data = opener.open(url).read().decode('utf-8', 'replace')
		except IOError:
			pass
		except:
			pass
		l = data.split('<hr size="1" color="#EEE" style="color: #EEE; background-color: #EEE; height: 1px; border: 0;" />')
		data = l[4]
		x = QRegExp('(<img src=.*/>)( <a href=.*</a>)')
		x.setMinimal(True)
		pos = 0
		startPos = 0
		toDisplayList = []
		while(pos != -1):
			pos = x.indexIn(data, startPos)
			startPos = pos + 21
			pair = []
			pair.append(x.cap(1).replace(QString(' align="absmiddle"'), QString('')))
			pair.append(x.cap(2).replace(QString('/topic/view/'), QString(self.babel.getUrl()) + QString('/topic/view/')))
			toDisplayList.append(pair)
		self.setPriority(QThread.TimeCriticalPriority)
		self.content = '<p></p><div><center><table cellspacing="6" width = "100%" border = "0"><tr><td bgcolor="#666666" width = "2"> </td><td><span style="color: #666666;"><b>INGC: </b> Hot Topics</span></td></tr>'
		for topic in toDisplayList[:8]:
			self.content = self.content + '<tr><td></td><td><table width="100%" border="0"><tr><td width="1"><table cellpadding = "1" bgcolor = "#eeeeee" border="0"><tr><td>' + topic[0] + '</td></tr></table></td><td><table width="100%" border="0"><tr><td>' + topic[1] + '</td></tr></table></td></tr></table></td></tr>'
		self.content = self.content + '</table></center></div>'
		self.stop = True
